package com.blog.controller;

import com.blog.common.ReturnResult;
import com.blog.pojo.Discuss;
import com.blog.pojo.User;
import com.blog.service.DiscussService;
import com.blog.util.Assert;
import com.blog.util.DateUtil;
import com.blog.util.ToolUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户管理
 *
 * @author JiaFuJun
 * @version v1.0
 * @date 2020-06-08
 */
@RestController
@RequestMapping(value = "/discuss")
public class DiscussController {
    @Autowired
    private DiscussService discussService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ReturnResult save(HttpServletRequest request, HttpServletResponse response, Discuss record, String isAdmin) {
        Assert.notNull(record.getDiscussName(), "昵称不能为空");
        Assert.notNull(record.getContent(), "评论内容不能为空");
        Assert.notNull(record.getArticleId(), "必须关联文章");
        if (isAdmin == null || isAdmin.equals("")) {
            Assert.notNull(record.getEmail(), "邮箱不能为空");
        }
        record.setIp(ToolUtil.getIpAddress(request));
        discussService.handle(record);
        return ReturnResult.ok();
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public ReturnResult del(HttpServletRequest request, HttpServletResponse response, Integer id) {
        if (id == null) {
            return ReturnResult.build("id不能为空");
        }

        discussService.del(id);
        return ReturnResult.ok();
    }

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public ReturnResult pageList(HttpServletRequest request, HttpServletResponse response, Discuss record,
                                 @RequestParam(value = "page", defaultValue = "1") Integer pageNo,
                                 @RequestParam(value = "limit", defaultValue = "20") Integer pageSize) {
        /**条件判断**/
        User user = (User) request.getSession().getAttribute("user");
        record.setArticleId(user.getId());
        PageInfo<Discuss> info = discussService.pageList(record, pageNo, pageSize);
        return ReturnResult.ok(info);
    }

    @RequestMapping(value = "/praise", method = RequestMethod.POST)
    public ReturnResult praise(Integer discussId) {
        Discuss discuss = new Discuss();
        discuss.setId(discussId);
        discuss.setPraiseNum(1);
        discussService.update(discuss);
        return ReturnResult.ok();
    }
}